<template>
  <div class="input-container">
    <el-form ref="formRef" :model="formData" :rules="formRules" class="basic-info-form-content">
      <div style="background-color: #FFFFFF;border-radius: 10px;padding: 20px 20px 0 20px">
        <div class="flex justify-content-space-between" style="gap: 20px">
          <div class="flex-auto box-container basic-form">
            <div class="sub-title">诊断信息</div>
            <div style="margin-top: 20px;color: #666666;font-size: 14px">主要诊断 (ICD-10) <span class="required-star"
                                                                                             style="color: red;">*</span>
            </div>
            <!-- 第一行 -->
            <el-row :gutter="20" style="margin-top: 20px">

              <el-col :span="12">
                <el-form-item prop="dRGCreateDRGICD10InfoVo.drgOrganizationKey">
                  <el-select v-model="formData.dRGCreateDRGICD10InfoVo.drgOrganizationKey"
                             :loading="drgICD10ListLoading" :remote-method="drgICD10CodeListFun" clearable filterable
                             placeholder="请输入诊断编码" remote @change="handleDiagnosisCodeChange">
                    <el-option v-for="(item,index) in selectList.drgICD10List" :key="item.drgOrganizationKey"
                               :label="item.drgOrganizationKey" :value="item.drgOrganizationKey"/>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="dRGCreateDRGICD10InfoVo.drgOrganizationName">
                  <el-select v-model="formData.dRGCreateDRGICD10InfoVo.drgOrganizationName"
                             :loading="drgICD10ListLoading" :remote-method="drgICD10NameListFun" clearable filterable
                             placeholder="请输入诊断名称" remote @change="handleDiagnosisNameChange">
                    <el-option v-for="(item,index) in selectList.drgICD10List" :key="item.drgOrganizationKey"
                               :label="item.drgOrganizationName" :value="item.drgOrganizationName"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="flex justify-content-space-between align-center">
              <div class="other-operation-info" style="color: #666666;font-size: 14px">其他诊断</div>
              <div class="flex align-center" style="margin-top: 10px;cursor: pointer;width: fit-content;padding-right: 40px" @click="addOtherDiagnosis">
                <img alt="" src="@/assets/static/add.png" style="width: 18px;height: 18px; margin-right: 5px">
                <div style="color: #1a8c7b;font-size: 14px">添加其他诊断</div>
              </div>
            </div>
            <!-- 其他诊断列表 -->
            <el-row v-for="(diagnosis, index) in formData.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems" :key="new Date().getTime()+(Math.random()*100000).toFixed(5)" :gutter="20" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item>
                  <el-select v-model="diagnosis.diseaseKey" :loading="diagnosisListLoading" :remote-method="diagnosisCodeListFun" clearable filterable placeholder="请输入其他诊断信息" remote @change="(val) => handleOtherDiagnosisCodeChange(val, index)">
                    <el-option v-for="(item,index) in selectList.diagnosisList" :key="item.diseaseKey" :label="item.diseaseKey" :value="item.diseaseKey"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item>
                  <el-select v-model="diagnosis.diseaseName" :loading="diagnosisListLoading" :remote-method="diagnosisNameListFun" clearable filterable placeholder="请输入其他诊断名称" remote @change="(val) => handleOtherDiagnosisNameChange(val, index)">
                    <el-option v-for="(item,index) in selectList.diagnosisList" :key="item.diseaseKey" :label="item.diseaseName" :value="item.diseaseName"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button circle icon="Delete" type="danger" @click="removeOtherDiagnosis(diagnosis)"></el-button>
              </el-col>
            </el-row>
          </div>
          <div class="flex-auto box-container basic-form">
            <div class="sub-title">手术信息</div>
            <div style="margin-top: 20px;color: #666666;font-size: 14px">主要手术 (ICD-9-CM3) <span class="required-star" style="color: red;">*</span>
            </div>
            <el-row :gutter="20" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item prop="dRGCreateDRGICD9InfoVo.drgOrganizationKey">
                  <el-select v-model="formData.dRGCreateDRGICD9InfoVo.drgOrganizationKey" :loading="drgICD19ListLoading" :remote-method="drgICD19CodeListFun" clearable filterable placeholder="请输入ICD-9-CM3编码" remote @change="handleOperationCodeChange">
                    <el-option v-for="(item,index) in selectList.drgICD19List" :key="item.drgOrganizationKey" :label="item.drgOrganizationKey" :value="item.drgOrganizationKey"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="dRGCreateDRGICD9InfoVo.drgOrganizationName">
                  <el-select v-model="formData.dRGCreateDRGICD9InfoVo.drgOrganizationName" :loading="drgICD19ListLoading" :remote-method="drgICD19NameListFun" clearable filterable placeholder="主要手术操作名称" remote @change="handleOperationNameChange">
                    <el-option v-for="(item,index) in selectList.drgICD19List" :key="item.drgOrganizationKey" :label="item.drgOrganizationName" :value="item.drgOrganizationName"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行 -->
            <div class="flex justify-content-space-between align-center">
              <div class="other-operation-info" style="color: #666666;font-size: 14px">其他手术信息</div>
              <div class="flex align-center" style="margin-top: 10px;cursor: pointer;width: fit-content;padding-right: 40px" @click="addOtherSurgeries">
                <img alt="" src="@/assets/static/add.png" style="width: 18px;height: 18px; margin-right: 5px">
                <div style="color: #1a8c7b;font-size: 14px">添加其他手术</div>
              </div>
            </div>

            <!-- 其他手术列表 -->
            <el-row v-for="(surgeries, index) in formData.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems" :key="new Date().getTime()+(Math.random()*100000).toFixed(5)" :gutter="20" style="margin-top: 20px">
              <el-col :span="12">
                <el-form-item>
                  <el-select v-model="surgeries.diseaseKey" :loading="surgeryListLoading" :remote-method="surgeryCodeListFun" clearable filterable placeholder="请输入其他手术操作编码" remote @change="(val) => handleOtherSurgeryCodeChange(val, index)">
                    <el-option v-for="(item,index) in selectList.surgeryList" :key="item.diseaseKey" :label="item.diseaseKey" :value="item.diseaseKey"/>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="10">
                <el-form-item>
                  <el-select v-model="surgeries.diseaseName" :loading="surgeryListLoading" :remote-method="surgeryNameListFun" clearable filterable placeholder="请输入其他手术操作名称" remote @change="(val) => handleOtherSurgeryNameChange(val, index)">
                    <el-option v-for="(item,index) in selectList.surgeryList" :key="item.diseaseKey" :label="item.diseaseName" :value="item.diseaseName"/>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="2">
                <el-button circle icon="Delete" type="danger" @click="removeOtherSurgeries(surgeries)"></el-button>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="flex justify-content-end" style="margin-top: 20px;">
          <el-form-item>
            <el-button style="width: 110px;margin-right: 20px" type="primary" @click="submitForm">
              <img alt="" src="@/assets/static/提交.png" style="width: 15px;margin-right: 10px">
              <div>提交分组</div>
            </el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="group-result" style="margin-top: 20px;background-color: #F9FAFB;border-radius: 10px;padding: 20px;" v-if="!(!!groupResult.drgWeight || !!groupResult.standardFee)">
      <aiLoading></aiLoading>
    </div>
    <div class="group-result" style="margin-top: 20px;background-color: #F9FAFB;border-radius: 10px;padding: 20px;" v-if="!!groupResult.drgWeight || !!groupResult.standardFee">
      <div class="box-container group-result-box" style="margin-top: 20px">
        <div style="font-size: 18px;font-weight: bolder">分组结果</div>
        <div style="font-weight: bolder;font-size:28px;margin-top: 10px;margin-bottom: 10px">{{groupResult.mdcCodeKey ?groupResult.mdcCodeKey : "null"}} - {{groupResult.mdcName}}</div>
        <div class="flex  flex-wrap" style="gap: 20px">
          <div style="width:50%;padding: 20px" class="align-center group-name" v-for="(item,index) in (groupResult.adrgCodeListItems)">
            <div class="flex align-center">
              <div class="name">{{item.diseaseKey}}</div>
              <div style="letter-spacing: 1px">{{item.diseaseName}} </div>
            </div>
            <div class="flex" style="margin-top: 10px">
              <div class="item flex align-center">
                <img src="@/assets/static/DRG类型.png" alt="">
                <div>{{item.unitName?item.unitName: "null"}}</div>
              </div>

              <div class="item flex align-center" style="margin: 0 20px">
                <img src="@/assets/static/MCC.png" alt="" style="">
                <div>{{item.mcCorCCTableName?item.mcCorCCTableName: "null"}}</div>
              </div>

              <div class="item flex align-center">
                <img src="@/assets/static/标准住院日.png" alt="" >
                <div>标准住院日: {{item.standardDay?item.standardDay: "null"}} 天</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="weight-pay-analysis ">
        <div class="sub-title">权重与支付分析</div>
        <div class="body-box flex justify-content-space-between" style="margin-top: 20px">
          <div class="item flex-auto flex align-center justify-content-center" style="text-align: center;border-right: 4px solid #E5E7EB;height: 160px">
            <div>
              <div class="val" style="color: #1a8c7b;font-weight: bolder;font-size: 30px">{{groupResult.drgWeight}}</div>
              <div class="label" style="font-size: 14px">病组权重</div>
            </div>
          </div>
          <div class="item flex-auto flex align-center justify-content-center" style="text-align: center;border-left: 1px solid #edf1f3;border-right: 1px solid #edf1f3;height: 160px">
            <div class="flex justify-content-space-between flex-auto">
              <div class="flex-auto ">
                <div class="val" style="color: #000000;font-weight: bolder;font-size: 30px">{{groupResult.diseaseGroupValue}}</div>
                <div class="label" style="font-size: 14px">病组总点数</div>
              </div>
              <div class="flex-auto ">
                <div class="val" style="color: #000000;font-weight: bolder;font-size: 30px">￥{{groupResult.standardFee}}</div>
                <div class="label" style="font-size: 14px">桂林年度点值费用</div>
              </div>
            </div>
          </div>
          <div class="item flex-auto payStyle flex justify-content-center align-center" style="text-align: center;height: 160px">
            <div style="background-color: #FFFFFF ;padding: 5px 50px;border-radius: 5px;">
              <div class="val" style="color: #1a8c7b;font-weight: bolder;font-size: 30px">￥{{groupResult.expectedFee}}</div>
              <div class="label" style="font-size: 14px">医保报销金额</div>
            </div>
          </div>
        </div>
      </div>
      <!-- AI开始 -->
      <div style="margin-top: 20px;padding: 20px;background-color: #FFFFFF;border-radius: 10px;">
        <div style="font-weight: bolder;font-size: 18px;color: #333333;margin-bottom: 10px;">人云联拓智能体指导建议</div>
        <div class="flex" style="padding: 20px;" v-if="isAiLoading">
          <div ref="outputRef" class="response-box">
            <!-- 渲染富文本内容 -->
            <div class="ai-response-content" v-html="renderedHTML"></div>
            <!-- 打字光标 -->
            <span v-if="isStreaming" class="cursor">|</span>
          </div>
        </div>
        <aiLoading v-else></aiLoading>
      </div>
      <!--   AI结束 -->

    </div>
    <el-dialog title="DRG分组信息提示" v-model="centerDialogVisible" width="50%"  :show-close="false">
      <div style="font-size: 14px;">
        <div style="margin: 10px 0">
          您当前录入的主要诊断(编码:11{{validResult.diagnosisDRGOrganizationKey}},名称:{{validResult.diagnosisDRGOrganizationName}})
          与主要手术(编码:{{validResult.surgeryDRGOrganizationKey}}，名称:{{validResult.surgeryDRGOrganizationName}})存在逻辑不匹配:</div>
        <div style="background-color: #FEFCEA;border-left: 4px solid #F3CE49;padding: 20px;">
          <div style="margin: 5px 0">1、核对主要诊断/手术编码是否录入错误 (是否属于同一MDC大组、亚目是否准确);</div>
          <div style="margin: 5px 0">2、确认是否遗漏更相关的主要手术 (如本次住院的核心治疗性手术);</div>
          <div style="margin: 5px 0">3、若临床确无其他手术,可选择"无手术操作" (如某些保守治疗的慢性病)。</div>
          <div style="margin-top: 10px">
            <el-alert title="继续提交可能导致DRG分组结果不正确，请谨慎操作！" type="error" show-icon></el-alert>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="goOnSubmitForm">继续提交</el-button>
          <el-button type="primary" @click="centerDialogVisible = false">返回修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {nextTick, ref,onMounted} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter, useRoute} from 'vue-router';
import debounce from 'lodash/debounce'
import aiLoading from '@/components/aiLoading/index.vue';
import {
  createDRGSimulation, createDRGSurgery, createDRGUserDisease,
  getDiagnosisList,
  getICD10DGList,
  getICD19DGList,
  getSurgeryList, updateDRGUserDisease
} from "@/api/drg/drg.js";
import MarkdownIt from "markdown-it/index.mjs";
import DOMPurify from "dompurify";
const validResult = ref({
  diagnosisDRGOrganizationKey: "",
  diagnosisDRGOrganizationName: "",
  surgeryDRGOrganizationKey: "",  // 手术信息
  surgeryDRGOrganizationName: ""  // 手术信息
});
const centerDialogVisible = ref(false);
const router = useRouter();
const route = useRoute();
const isAiLoading = ref(false);
const medications = ref([
  {
    drug: '抗血小板药物：阿司匹林',
    dosage: '100mg qd',
    indication: '（依据：冠心病二级预防）'
  },
  {
    drug: '他汀类药物：阿托伐他汀',
    dosage: '20mg qn',
    indication: '（依据：LDL-C>2.6mmol/L）'
  },
  {
    drug: 'β受体阻滞剂：美托洛尔缓释片',
    dosage: '47.5mg qd',
    indication: '（依据：心绞痛症状控制）'
  },
  {
    drug: 'ACEI类药物：培哚普利',
    dosage: '4mg qd',
    indication: '（依据：合并高血压及心衰）'
  }
]);
const treatmentPlan = ref([
  '入院24h内完成冠脉造影评估',
  '术后48h内启动抗心肌酶谱及心电图',
  '术后72h内启动心脏康复评估',
  '出院前完成药物调整及随访计划'
]);
const drgSchemes = ref([
  {
    title: '冠状动脉粥样硬化性心脏病伴心绞痛',
    code: 'FR21',
    groupName: '心力衰竭、休克，伴严重合并症或并发症',
    weight: '1.82',
    multiplier: '1.25x',
    avgDays: '7天'
  },
  {
    title: '冠状动脉粥样硬化性心脏病不稳定心绞痛',
    code: 'FR23',
    groupName: '冠状动脉粥样硬化性心脏病不稳定心绞痛',
    weight: '1.90',
    multiplier: '1.30x',
    avgDays: '6天'
  }
]);
const selectList = ref({
  drgICD10List: [], // 主要诊断信息
  drgICD19List: [], //主要手术信息
  diagnosisList: [], //其他诊断信息
  surgeryList: [], //其他手术信息
});
const formRules = {
  'dRGCreateDRGICD10InfoVo.drgOrganizationKey': [{required: true, message: '请输入主要诊断编码', trigger: 'change'}],
  'dRGCreateDRGICD10InfoVo.drgOrganizationName': [{required: true, message: '请输入主要诊断名称', trigger: 'change'}],
  'dRGCreateDRGICD9InfoVo.drgOrganizationKey': [{required: true, message: '请输入主要手术操作编码', trigger: 'change'}],
  'dRGCreateDRGICD9InfoVo.drgOrganizationName': [{required: true, message: '请输入主要手术操作名称', trigger: 'change'}],
};
const groupResult = ref({}); // 分组结果
const formRef = ref(null);
const formData = ref({
  dRGCreateDRGICD10InfoVo: {    // 主要诊断信息
    drgOrganizationKey: "", // 主要诊断DRG分组Key
    drgOrganizationName: "", // 主要诊断DRG分组名称
    drgOrganizationParentId: "", // 主要诊断父级key标识
    dRGCreateDRGICD10InfoItems: []
  },
  dRGCreateDRGICD9InfoVo: {
    drgOrganizationKey: "",  // 主要手术主要DRG分组Key
    drgOrganizationName: "",  // 主要诊断DRG分组名称
    drgOrganizationParentId: "", // 主要诊断父级key标识
    drgCreateDRGICD9InfoItems: []
  },
});
const drgICD10ListLoading = ref(false);// 添加主要诊断相关状态
const diagnosisListLoading = ref(false);// 其他诊断相关状态
const drgICD19ListLoading = ref(false);// 添加主要手术相关状态
const surgeryListLoading = ref(false);// 添加其他手术相关状态
// 请求主要诊断编码数据
const drgICD10CodeListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD10ListLoading.value = true
    const result = await getICD10DGList({organizationName: "", organizationKey: query});
    selectList.value.drgICD10List = result.data.data;
    drgICD10ListLoading.value = false;
  } else {
//    ElMessage.warning('主要诊断Code不能为空!');
  }
}, 500)
// 请求主要诊断名称数据
const drgICD10NameListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD10ListLoading.value = true
    const result = await getICD10DGList({organizationName: query, organizationKey: ""});
    selectList.value.drgICD10List = result.data.data;
    drgICD10ListLoading.value = false;
  } else {
    //  ElMessage.warning('主要诊断Name不能为空!');
  }
}, 500)
//请求其他诊断数据
const diagnosisCodeListFun = debounce(async (query) => {
  if (query !== '') {
    diagnosisListLoading.value = true
    const result = await getDiagnosisList({drgType: 0, diseaseKey: query, diseaseName: ""}); // 其他诊断信息
    selectList.value.diagnosisList = result.data.data;
    diagnosisListLoading.value = false;
  } else {
    //  ElMessage.warning('其他诊断Code不能为空!');
  }
}, 500)
//请求其他诊断数据
const diagnosisNameListFun = debounce(async (query) => {
  if (query !== '') {
    diagnosisListLoading.value = true
    const result = await getDiagnosisList({drgType: 0, diseaseKey: "", diseaseName: query}); // 其他诊断信息
    selectList.value.diagnosisList = result.data.data;
    diagnosisListLoading.value = false;
  }
}, 500)
//请求主要手术数据
const drgICD19CodeListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD19ListLoading.value = true
    const result = await getICD19DGList({organizationName: "", organizationKey: query}); // 主要手术信息
    result.data.data.unshift({
      id: "00000000-0000-0000-0000-000000000000",
      drgOrganizationKey: "0",
      drgOrganizationName: "无手术操作",
      drgOrganizationParentId: "0",
      drgLeve: 0,
      creationTime: "2025-09-16 16:01:06",
      isDeleted: false,
      extraProperties: {},
      concurrencyStamp: ""
    });
    selectList.value.drgICD19List = result.data.data;
    console.log("主要手术信息: ", selectList.value.drgICD19List)
    drgICD19ListLoading.value = false;
  }
}, 500)
//请求主要手术数据
const drgICD19NameListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD19ListLoading.value = true
    const result = await getICD19DGList({organizationName: query, organizationKey: ""}); // 主要手术信息
    result.data.data.unshift({
      id: "00000000-0000-0000-0000-000000000000",
      drgOrganizationKey: "0",
      drgOrganizationName: "无手术操作",
      drgOrganizationParentId: "0",
      drgLeve: 0,
      creationTime: "2025-09-16 16:01:06",
      isDeleted: false,
      extraProperties: {},
      concurrencyStamp: ""
    });
    selectList.value.drgICD19List = result.data.data;
    console.log("主要手术信息: ", selectList.value.drgICD19List)
    drgICD19ListLoading.value = false;
  }
}, 500)
// 请求其他手术数据
const surgeryCodeListFun = debounce(async (query) => {
  if (query !== '') {
    surgeryListLoading.value = true
    const result = await getSurgeryList({drgType: 1, diseaseKey: query, diseaseName: ""});  // 其他手术信息
    selectList.value.surgeryList = result.data.data;
    surgeryListLoading.value = false;
  }
}, 500)
// 请求其他手术数据
const surgeryNameListFun = debounce(async (query) => {
  if (query !== '') {
    surgeryListLoading.value = true
    const result = await getSurgeryList({drgType: 1, diseaseKey: "", diseaseName: query});  // 其他手术信息
    selectList.value.surgeryList = result.data.data;
    surgeryListLoading.value = false;
  }
}, 500)
// 添加其他诊断
const addOtherDiagnosis = () => {
  formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.push({
    diseaseKey: '',
    diseaseName: '',
    diseaseTableName: ''
  });
}
// 添加其他手术
const addOtherSurgeries = () => {
  formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.push({
    diseaseKey: '',
    diseaseName: '',
    diseaseTableName: ''
  });
}
const removeOtherDiagnosis = (item) => {
  const index = formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.indexOf(item);
  if (index !== -1 && formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.length >= 1) {
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.splice(index, 1)
  } else {
    ElMessage.warning('其他诊断已全部删除!'); // 删除其他诊断
  }
}
const removeOtherSurgeries = (item) => {
  const index = formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.indexOf(item);
  if (index !== -1 && formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.length >= 1) {
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.splice(index, 1)
  } else {
    ElMessage.warning('其他手术已全部删除!'); // 删除其他诊断
  }

  //drgCreateDRGICD9InfoItems.value.length > 0?drgCreateDRGICD9InfoItems.value.splice(index, 1):ElMessage.warning('其他手术已全部删除!'); // 删除其他手术
}
const getSelectList = async () => {
  Promise.all([
    getICD10DGList(), // 主要诊断信息
    getICD19DGList(), // 主要手术信息
    getDiagnosisList({drgType: 0}),  // 其他诊断信息
    getSurgeryList({drgType: 1}),  // 其他手术信息

  ]).then(res => {
    if (Array.isArray(res) && res.length > 0) {
      selectList.value.drgICD10List = res[0].data.data;
      res[1].data.data.unshift({
        id: "00000000-0000-0000-0000-000000000000",
        drgOrganizationKey: "0",
        drgOrganizationName: "无手术操作",
        drgOrganizationParentId: "0",
        drgLeve: 0,
        creationTime: "2025-09-16 16:01:06",
        isDeleted: false,
        extraProperties: {},
        concurrencyStamp: ""
      });
      selectList.value.drgICD19List = res[1].data.data;
      selectList.value.diagnosisList = res[2].data.data;
      selectList.value.surgeryList = res[3].data.data;
    }
  })
};
const createDRGSurgeryInfo = async (data) => {
  let result = await createDRGSurgery(data);
  return result
}
// 提交表单方法
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let dRGCreateDRGICD10InfoVo = {
        drgOrganizationKey: formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationKey,
        drgOrganizationName: formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationName,
        drgOrganizationParentId: formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId
      };
      let dRGCreateDRGICD9InfoVo = {
        drgOrganizationKey:  formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationKey,
        drgOrganizationName: formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationName,
        drgOrganizationParentId:formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId
      }
      // 验证分组方法
      let result = await createDRGSurgeryInfo({dRGCreateDRGICD10InfoVo, dRGCreateDRGICD9InfoVo});
      if (result.status == 200 && result.data.code == 200){
        await goOnSubmitForm();
      }else if (result.status == 200 && result.data.code == 400){
        validResult.value = result.data.data;
        centerDialogVisible.value = true;
      }
    } else {
      ElMessage.error('请填写完整信息！');
    }
  });
};
// 继续提交
const goOnSubmitForm = async () => {
  centerDialogVisible.value = false;
  let requestData = await createDRGSimulation(formData.value);
  if (requestData.status == 200 && requestData.data.code == 200){
    groupResult.value = requestData.data.data;
    ElMessage.success('分组模拟成功!');
    const param = parameterExtract(formData.value);  // 构建AI接口参数
    isAiLoading.value = false;
    await startStream(param)
  }else {
    ElMessage.error('分组模拟失败!');
  }
};
// 重置表单方法
const resetForm = () => {
  formRef.value.resetFields();
};
// 处理主要诊断编码变化
const handleDiagnosisCodeChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD10List.find(item => item.drgOrganizationKey === value);
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationName = selectedItem.drgOrganizationName;
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationName = "";
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = "";
  }

};
// 处理主要诊断名称变化
const handleDiagnosisNameChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD10List.find(item => item.drgOrganizationName === value);
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationKey = selectedItem.drgOrganizationKey;
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationKey = "";
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = "";
  }
};
// 处理其他诊断编码变化
const handleOtherDiagnosisCodeChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.diagnosisList.find(item => item.diseaseKey === value);
    console.log("处理其他诊断编码变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseName = selectedItem.diseaseName;
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseName = "";
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = "";
  }
};
// 处理其他诊断名称变化
const handleOtherDiagnosisNameChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.diagnosisList.find(item => item.diseaseName === value);
    console.log("处理其他诊断名称变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseKey = selectedItem.diseaseKey;
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseKey = "";
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = "";
  }
};
// 处理主要手术操作编码变化
const handleOperationCodeChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD19List.find(item => item.drgOrganizationKey == value);
    console.log("处理主要手术操作编码变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationName = selectedItem.drgOrganizationName;
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationName = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = "";
  }
};
// 处理主要手术操作名称变化
const handleOperationNameChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD19List.find(item => item.drgOrganizationName == value);
    console.log("处理主要手术操作名称变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationKey = selectedItem.drgOrganizationKey;
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationKey = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = "";
  }
};
// 处理其他手术编码变化
const handleOtherSurgeryCodeChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.surgeryList.find(item => item.diseaseKey === value);
    console.log("处理其他手术编码变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseName = selectedItem.diseaseName;
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseName = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = "";
  }
};
// 处理其他手术名称变化
const handleOtherSurgeryNameChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.surgeryList.find(item => item.diseaseName === value);
    console.log("处理其他手术名称变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseKey = selectedItem.diseaseKey;
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseKey = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = "";
  }
};
// 参数截取
const parameterExtract = (data)=>{
  let diagnosisInfo = "主要诊断:" + data.dRGCreateDRGICD10InfoVo.drgOrganizationName;   // 诊断信息
  let surgeryInfo = "主要手术:" + data.dRGCreateDRGICD9InfoVo.drgOrganizationName; // 手术信息
  data.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.forEach(item => {
    diagnosisInfo += (",其他诊断:"+item.diseaseName);
  });
  data.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.forEach(item => {
    surgeryInfo += (",其他手术:"+item.diseaseName);
  });
  return (diagnosisInfo + "," +surgeryInfo);
}



// ==================== 配置区 ====================
//const API_URL = 'https://dashscope.aliyuncs.com/api/v2/apps/agent/A/compatible-mode/v1/responses'
// 基础 URL
//const API_URL = 'https://dashscope.aliyuncs.com/api/v2/apps/agent/9c8cdc23a81e48cc9979e9543ac06c4f/compatible-mode/v1/responses'
const API_URL = 'https://dashscope.aliyuncs.com/api/v2/apps/agent/a6248bff9b9c4f0d819bc0e90adb3629/compatible-mode/v1/responses'
const API_KEY = 'sk-69a5314907eb4feea7c1a371c6778a51' // ⚠️ 替换为你自己的有效 Key
// ==================== 响应式数据 ====================
const isStreaming = ref(false)
const renderedHTML = ref('')
const outputRef = ref(null)
// ==================== 初始化 markdown-it（含表格修复插件）====================
const md = new MarkdownIt({
  html: false,
  breaks: true,
  typographer: true
})
// 🔧 插件：检测并转换“空格分隔”的纯文本表格为 Markdown 表格
function detectAndConvertTextTable(text) {
  const lines = text.trim().split('\n')
  let headers = []
  let rows = []

  for (const line of lines) {
    const trimmed = line.trim()
    if (!trimmed) continue

    // 使用多个空格或制表符分割
    const cells = trimmed.split(/\s{2,}|\t/).filter(Boolean)
    if (cells.length < 2) continue // 至少两列

    // 判断是否为表头：不含明显数字/百分比
    const hasNumbers = /[\d\.]+%?/.test(trimmed)
    if (!headers.length && !hasNumbers) {
      headers = cells
    } else if (hasNumbers && cells.length >= headers.length) {
      // 数据行：补全或截断以匹配表头长度
      const row = cells.slice(0, headers.length)
      rows.push(row)
    }
  }

  // 构造 Markdown 表格
  if (headers.length >= 2 && rows.length >= 1) {
    const headerRow = '| ' + headers.join(' | ') + ' |'
    const separatorRow = '| ' + headers.map(() => '---').join(' | ') + ' |'
    const dataRows = rows.map(row => '| ' + row.join(' | ') + ' |').join('\n')
    return [headerRow, separatorRow, dataRows].join('\n')
  }

  return null
}
// ✅ 增强 render 方法：自动修复文本表格
const originalRender = md.render.bind(md)
md.render = function (content) {
  let enhancedContent = content

  // 查找可能的表格块（连续多行，每行有多个空格）
  const potentialBlocks = enhancedContent.match(/(?:^|\n)(?:[^\n]+\s+[^\n]+\n?)+/g)
  if (potentialBlocks) {
    potentialBlocks.forEach(block => {
      const cleanedBlock = block.trim()
      if (!cleanedBlock || cleanedBlock.startsWith('|') || cleanedBlock.includes('---')) return

      const tableMarkdown = detectAndConvertTextTable(cleanedBlock)
      if (tableMarkdown) {
        enhancedContent = enhancedContent.replace(cleanedBlock, tableMarkdown)
      }
    })
  }

  try {
    return originalRender(enhancedContent)
  } catch (e) {
    console.error('[Markdown] 渲染失败:', e)
    return `<p style="color:red">❌ 内容渲染错误</p>`
  }
}
// ==================== 流式请求 ====================
const startStream = async (aiParam) => {
  if (isStreaming.value) return
  renderedHTML.value = ''
  isStreaming.value = true
  let accumulatedText = ''
  try {
    const payload = {
      input: [
        {
          type: 'message',
          role: 'user',
          content: [
            {
              type: 'input_text',
              text: aiParam
            }
          ]
        }
      ],
      stream: true
    }
    console.log('API_URL :'+ API_URL)
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify(payload)
    })

    if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`)
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''
    isAiLoading.value = true;
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop()
      for (const line of lines) {
        const trimmed = line.trim()
        if (!trimmed.startsWith('data:')) continue

        const dataStr = trimmed.slice(5).trim()
        if (!dataStr || dataStr === '[DONE]') continue

        try {
          const data = JSON.parse(dataStr)
          if (data.type === 'response.output_text.delta' && typeof data.delta === 'string') {
            const deltaText = data.delta.replace(/<br>/g, '')
            accumulatedText += deltaText

            // 使用增强版 markdown-it 渲染（含表格修复）
            const unsafeHtml = md.render(accumulatedText)
            renderedHTML.value = DOMPurify.sanitize(unsafeHtml)

            // 自动滚动到底部
            await nextTick()
            outputRef.value?.scrollTo?.(0, outputRef.value.scrollHeight)
          }
        } catch (err) {
          console.warn('[解析失败]', err, dataStr)
        }
      }
    }
    // 结束标记
    const finalText = accumulatedText + '\n\n✅ 报告生成完成。'
    const unsafeHtml = md.render(finalText)
    renderedHTML.value = DOMPurify.sanitize(unsafeHtml)
  } catch (error) {
    console.error('[请求失败]', error)
    renderedHTML.value = `<span style="color:red">❌ 请求失败：${error.message}</span>`
  } finally {
    isStreaming.value = false

  }
}

onMounted(() => {
  getSelectList();
})
</script>
<style lang='scss' scoped>
.input-container {
  padding: 0 20px;
  border-radius: 5px;
  margin-top: 20px;

  .box-container {
    background-color: #F9FAFB;
    padding: 20px;
    border-radius: 5px;
  }

  .basic-form {
    .sub-title {
      font-size: 18px;
      font-weight: bolder;
      color: #333333;
    }
  }

  .description-header {
    margin-bottom: 10px;
  }

  .description-container {
    .complication-item {
      padding: 5px 0;

      .complication-type {
        width: 80px;
      }

      .complication-code {
        background-color: #c3e8cf;
        text-align: center;
        border-radius: 5px;
        padding: 4px 5px;
        color: #68A197;
        font-size: 14px;
      }

      .complication-name {
        margin-left: 20px;
        text-align: center;
        color: #333333;
      }
    }
  }

  .treatment-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }

  .treatment-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px 20px;
    transition: all 0.2s ease;
  }

  .treatment-item:hover {
    background-color: #e6f7ff;
    transform: translateY(-1px);
  }

  .icon-container {
    width: 40px;
    height: 40px;
    margin-right: 12px;
  }

  .content {
    flex: 1;
  }

  .main-text {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }

  .sub-text {
    font-size: 14px;
    color: #666;
  }

  .switch-container {
    margin-left: 12px;
  }
}
.group-result-box {
  background-color: transparent !important;
  background: url("../../../assets/static/分组结果背景.png") no-repeat center center;
  background-size: 100% 100%;
  borerder-radius: 10px !important;
  width: 100%;
  height: 260px;

  .group-name {
    background-color: rgba(102, 102, 102, 0.57);
    margin: 20px 0;
    border-radius: 10px;
    width: fit-content;
    padding: 10px 20px;

    .name {
      font-weight: bolder;
      font-size: 24px;
      margin-right: 10px;
    }
  }

  .item {
    img {
      margin-right: 5px;
      width: 30px;
      display: block;
      background-color: rgba(26, 140, 123, 0.21);
      border-radius: 50%;
    }
  }
}
.weight-pay-analysis {
  background-color: #ffffff;
  margin-top: 20px;
  padding: 40px 20px;
  border-radius: 5px;

  .sub-title {
    font-weight: bolder;
    font-size: 18px;
    color: #333333;
  }

  .item {
    .label {
      color: #7c7676;
      font-size: 16px;
    }
  }

  .sign-card {
    margin-top: 20px;
    position: relative;
    background-color: #FFFFFF;

    border-radius: 5px;
    /* 自定义文字容器样式 */
    .progress-text {
      position: absolute;
      color: #333;
      display: flex;
      justify-content: space-between;
      width: 100%;
    }

    .percent-text {
      font-size: 14px;
      text-align: end;
    }

    :deep(.el-progress-bar__inner) {
      background-color: #1a8c7b !important;
    }

    :deep(.el-progress) {
      display: block;
    }

    .sign-info {
      font-size: 12px;
    }
  }
}
.ai-analysis{
  .sub-title {
    font-weight: bolder;
    font-size: 18px;
    color: #333333;
  }
}
.drg-scheme-list {
  margin-top: 10px;
  .scheme-item {
    background-color: #F9FAFB;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 10px;
    .scheme-title {
      font-weight: bold;
      color: #1A8C7B;
      margin-bottom: 12px;
    }
    .detail-row {
      display: flex;
      margin-bottom: 8px;
      font-size: 14px;
      .label {
        width: 100px;
        color: #666;
        font-weight: 500;
      }
      .value {
        font-weight: bolder;
        flex: 1;
        color: #333;
      }
    }
  }
}
.payStyle{
  background: url("../../../assets/static/img.png") no-repeat center center;
  background-size: cover ;
  borerder-radius: 10px !important;
}



/* 通用iframe样式 */
.section-iframe {
  width: 100%;
  border: 1px solid #ccc;
  min-height: 100px; /* 初始最小高度 */
}

.wrapper {
  margin-top: 20px;
}
.weight-pay-analysis {
  background-color: #ffffff;
  padding: 40px 20px;
  border-radius: 5px;
  .sub-title {
    font-weight: bolder;
    font-size: 18px;
    color: #333333;
  }

  .item {
    .label {
      color: #7c7676;
      font-size: 16px;
    }
  }

  .sign-card {
    margin-top: 20px;
    position: relative;
    background-color: #FFFFFF;
    padding: 40px 20px;
    border-radius: 5px;
    /* 自定义文字容器样式 */
    .progress-text {
      position: absolute;
      color: #333;
      display: flex;
      justify-content: space-between;
      width: 100%;
    }

    .percent-text {
      font-size: 14px;
      text-align: end;
    }

    :deep(.el-progress-bar__inner) {
      background-color: #1a8c7b !important;
    }

    :deep(.el-progress) {
      display: block;
    }

    .sign-info {
      font-size: 12px;
    }
  }
}

// =========

.response-box {
  width: 100%;
  padding: 16px;
  overflow-y: auto;
  line-height: 1.7;
  font-size: 15px;
  background-color: #ffffff;
  color: #333333;
}

/* ==================== 富文本样式 ==================== */
.ai-response-content h1,
.ai-response-content h2,
.ai-response-content h3 {
  margin: 1em 0 0.5em;
  color: #07173b;
}
.ai-response-content h1 {
  font-size: 1.8em;
  text-align: center;
}
.ai-response-content h2 {
  font-size: 1.5em;
  border-left: 4px solid #007bff;
  padding-left: 12px;
}
.ai-response-content h3 {
  font-size: 1.3em;
  color: #34495e;
}
:global(.ai-response-content table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
  font-size: 0.95em;
  border: 1px solid #2c2a2a;
}
:global(.ai-response-content th,
.ai-response-content td ){
  border: 1px solid #ccc;
  padding: 8px 12px;
  text-align: center;
}
:global(.ai-response-content th ){
  background-color: #f0f5ff;
  font-weight: 600;
  color: #1a3b6d;
}
:global(.ai-response-content tr:nth-child(even) ){
  background-color: #f9f9f9;
}
:global(.ai-response-content p){
  margin: 0.6em 2;
}
:global(.ai-response-content ul) {
  margin-left: 40px;
  margin: 0.6em 1;
  padding-left: 1;
}
:global(.ai-response-content ol) {
  margin-left: 40px;
  margin: 0.6em 2;
  padding-left: 2;
}
:global(.ai-response-content li ){
  margin: 0.6em 1.2;
  padding-left: 20px;
}
.cursor {
  animation: blink 1.2s step-end infinite;
  color: #007bff;
  font-weight: bold;
  font-size: 1.1em;
}
:global(.ai-message table ){
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
  font-size: 0.95em;
}
:global(.ai-message th,
.ai-message td ){
  border: 1px solid #ccc;
  padding: 6px 10px;
  text-align: left;
}
:global(.ai-message th ){
  background-color: #f0f5ff;
  font-weight: 600;
}
:global(.ai-message tr:nth-child(even) ){
  background-color: #f9f9f9;
}
@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

</style>
